package cn.itcast.controller.log;

import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

@Component
@Aspect
public class LogAspect {
    @Autowired
    private HttpSession session;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SysLogService sysLogService;

    @Around("execution(* cn.itcast.controller.*.*.*(..))")
    public Object saveSysLog(ProceedingJoinPoint pjp) throws Throwable {
        User user = (User) session.getAttribute("loginUser");
        if (user==null){
            return "forward:/login.jsp";
        }
        SysLog sysLog = new SysLog();
        sysLog.setId(UUID.randomUUID().toString());
        sysLog.setTime(new Date());
        sysLog.setUserName(user.getUserName());
        sysLog.setCompanyId(user.getCompanyId());
        sysLog.setCompanyName(user.getCompanyName());
        sysLog.setIp(request.getRemoteAddr());// 设施操作的ip地址
        // 获取Signature的实现类对象
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        sysLog.setMethod(method.getName());
        // 获取注解对象
        RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
        sysLog.setAction(requestMapping.name());

        sysLogService.save(sysLog);
        return pjp.proceed();
    }
}
